<script setup>
import Recorder from '@/utils/Asr/recorder.js'
import TTSRecorder from '@/utils/TTs2/ttsRecorder.js';
import { useWebSocket } from '@vueuse/core'
import { ref, onMounted, onUnmounted  } from 'vue'
const VITE_WS_URL = import.meta.env.VITE_WS_URL
let recorder = null
let ws = null
const ttsRecorder = new TTSRecorder();

// 引用DOM元素
const resultTextRef = ref(null)
const startAsrRef = ref(null)
const stopAsrRef = ref(null)

// 状态变量
const statusText = ref('准备就绪')
const mediaRecorder = ref(null)
const audioContext = ref(null)
const stream = ref(null)
const isRecording = ref(false)

// 获取麦克风权限
const getMicrophonePermission = async () => {
  try {
    statusText.value = '正在请求麦克风权限...'
    stream.value = await navigator.mediaDevices.getUserMedia({ audio: true })
    statusText.value = '麦克风权限已获取'
    startAsrRef.value.disabled = false
    recorder = new Recorder({
      sampleBits: 16,
      sampleRate: 16000,
      numChannels: 1,
      compiling:true,
      silentThreshold:3
    });
    return true
  } catch (error) {
    console.error('获取麦克风权限失败:', error)
    statusText.value = '获取麦克风权限失败'
    return false
  }
}

const result = (resultData) =>{
  
}





const useSocket = (params) =>{
    const url = VITE_WS_URL+'/asr/websocket'
    const {status, close, send, open, ws} = useWebSocket(`${url}`,{
        heartbeat:  {
            interval: 1000,
            pongTimeout: 500,
        },
        onMessage(ws,event){             
            if(event.data){
               let {c} =event.data;
               if(c === '100'){
                let {d} =event.data;
                  if(d !== "finished"){
                    resultTextRef.value.innerHTML += d;
                  }
              }
            }
        },
        onDisconnect(ws,event){
            console.log('websocket连接关闭');
        },
        onError(ws,event){
            console.log('websocket连接错误');
        },
        onConnect(ws,event){
            console.log('websocket连接成功');
        }
    })
    return {status, close, send, open, ws}
}

let interval = null;
const startSendRecording = () =>{
    if(!ws|| ws?.status?.value === 'CLOSED'){
        ws = useSocket()
    }
    console.log("status",ws.status.value);
    
    if(ws.status.value === "CONNECTING"){
      ws.send('started');
      interval = setInterval(() => {
          let data = recorder.getNextData()
          if(data){
              ws.send(data);
              console.log(data);            
          }
          console.log("status_send",ws.status.value);
      }, 40)
    }
}


// 开始录音
const startAsr = () => {
    if(!getMicrophonePermission()){
        statusText.value = '获取麦克风权限失败'
        return 
    }
  if (!stream.value) {
    getMicrophonePermission().then(success => {
      if (success) startRecording()})
  } else {
    startRecording()
  }
}


// 开始录音的具体实现
const startRecording = () => {
  if (isRecording.value) return
  
  isRecording.value = true
  statusText.value = '正在录音...'
  startAsrRef.value.disabled = true
  stopAsrRef.value.disabled = false
  
  // 这里可以添加录音相关的逻辑
  console.log("开始录音")
  
    recorder.start().then(()=>{
          startSendRecording()
    }).catch((err)=>{
        console.log(err);
    });
}

// 停止录音
const stopAsr = async () => {
  if (!isRecording.value) return
  console.log(1);
  console.log("status",ws.status.value);
  
  isRecording.value = false
  statusText.value = '录音停止'
  startAsrRef.value.disabled = false
  stopAsrRef.value.disabled = true
  if(recorder){
    await recorder.stop()
    clearInterval(interval);
  }
  setTimeout(() => {    
    ws.send('finished');
  }, 500)
}

// 键盘事件处理
const handleKeydown = (event) => {
  if (event.code === "Space" && !isRecording.value) {
    startAsr()
    window.removeEventListener("keydown", handleKeydown)
  }    
}

const handleKeyup = (event) => {
  if (event.code === "Space" && isRecording.value){
    stopAsr()
    window.addEventListener("keydown", handleKeydown)
  }
}

// 组件挂载时初始化
onMounted(() => {
  // 添加键盘事件监听
  window.addEventListener("keydown", handleKeydown)
  window.addEventListener("keyup", handleKeyup)
})

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener("keydown", handleKeydown)
  window.removeEventListener("keyup", handleKeyup)
  
  // 释放媒体流
  if (stream.value) {
    stream.value.getTracks().forEach(track => track.stop())
  }
  
  // 关闭音频上下文
  if (audioContext.value) {
    audioContext.value.close()
  }
  if(ws){
    ws.close()
  }
})
const playAudio = () => {
}
</script>

<template>
  <div class="containerASR">
    <h1 class="title">语音识别</h1>
    <div class="fun_view">
      <div class="fun">
        <div class="controls">
          <button ref="startAsrRef" @click="startAsr" :disabled="isRecording">开始录音</button>
          <button ref="stopAsrRef" @click="stopAsr" :disabled="!isRecording">停止录音</button>
        </div>
        <div class="status">
          <p id="statusText">{{ statusText }}</p>
        </div>
      </div>
    </div>
    
    <div class="result">
      <h2 class="text">识别结果：</h2>
      <div class="resultText" >
        <div ref="resultTextRef" contenteditable="true">
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.containerASR{
    width: 100%;
    height: 100%;
    margin: auto;
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    user-select: none;
    .title{
        color: #333;
    }
    .fun_view{
        height: 120px;
        display: flex;
        .fun{
            flex: 1;
            .controls {
                display: flex;
                justify-content: center;
                margin: 20px 0;
                gap: 10px;
                button {
                    padding: 10px 20px;
                    font-size: 16px;
                    cursor: pointer;
                    background-color: #4CAF50;
                    color: white;
                    border: none;
                    border-radius: 4px;
                    transition: background-color 0.3s;
                    &:hover {
                        background-color: #45a049;
                    }
                    &:disabled {
                        background-color: #cccccc;
                        cursor: not-allowed;
                    }
                }
            }
            .status {
                text-align: center;
                margin: 10px 0;
                font-size: 16px;
                color: #666;
            }
        }
        .view{
            flex: 1;
            width: 100%;
            height: 100%;
            background: #f9f9f9;
            .canvas {
                width: 100%;
                height: 100%;
            }
        }
    }
   
    .result {
        height:  calc(100% - 180px);
        margin-top: 20px;
        padding: 15px;
        background-color: #f9f9f9;
        border-radius: 4px;
        border: 1px solid #ddd;
        flex: 1;
        display: flex;
        flex-direction: column;
        .text{
          margin-bottom: 10px;
        }
        .resultText{
            height:100% ;
            line-height: 1.5;
            padding: 10px;
            user-select: text;
            overflow-y: auto;     
            white-space: pre-wrap;
            word-break: break-word;
            box-sizing: border-box;
            overflow-y: auto;
        }
    }

}
</style>
